//
//  WBNetworkManager.swift
//  Weibo
//
//  Created by wade on 17/2/22.
//  Copyright © 2017年 wade. All rights reserved.
//

import UIKit
import AFNetworking

enum WBHTTPMethod {
    case GET
    case POST
    case PUT
    case DELETE
}



class WBNetworkManager: AFHTTPSessionManager {

    lazy var userAccount = WBUserAccount()
    
//    var accessToken : String? //= "2.00CDxNMB5_cVCEcf68fcfafe07MBvm"
//    
//    var uid:String?
    
    static let shared : WBNetworkManager = {
    
        let instance = WBNetworkManager()
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    
    }()
    
    var userLogon : Bool {
    
        return userAccount.access_token != nil
    
    }
    
    func request(method:WBHTTPMethod = .GET,URLString:String,parameters:[String:Any]?,completion:@escaping (Any?,Bool)->())  {
        
        let success = {
        
            (task:URLSessionDataTask,json:Any) -> () in
        
            completion(json, true)
        }
        
        let failure = {
        
            (task:URLSessionDataTask?,error:Error) -> () in
        
            if (task?.response as? HTTPURLResponse)?.statusCode == 403{
            
                print("accessToken 过期了")
                
                // FIXME : accessToken 过期了
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            
            }
            
            
            completion(nil,false)
            return
            
        }
        
        if userAccount.access_token == nil {
            
            print("accessToken 为空")
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
            completion(nil,false)
            return
        }
        
        
        var par = parameters
        
        if par == nil
        {
            par = [String:Any]()
        }
        
        par!["access_token"] = userAccount.access_token
        
        if method == .GET
        {
            get(URLString, parameters: par, progress: nil, success: success, failure: failure)
        }
        else if method == .POST
        {
            post(URLString, parameters: par, progress: nil, success: success, failure: failure)
        }
        else if method == .PUT
        {
            put(URLString, parameters: par, success: success, failure: failure)
        }
        else if method == .DELETE
        {
            delete(URLString, parameters: par, success: success, failure: failure)
        }
        
        
    }
    
    
    func requestToken(method: WBHTTPMethod = .GET, URLString: String, parameters: [String: Any]?, completion: @escaping (Any?,Bool)->()) {
        
        // 成功回调
        let success = { (task:URLSessionDataTask,json:Any) -> () in
            
            completion(json, true)
        }
        
        // 失败回调
        let failure = { (task:URLSessionDataTask?,error:Error) -> () in
            
            // 针对 403 处理用户 token 过期
            // 对于测试用户(应用程序还没有提交给新浪微博审核)每天的刷新量是有限的！
            // 超出上限，token 会被锁定一段时间
            // 解决办法，新建一个应用程序！
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                print("Token 过期了")
                
                // 发送通知，提示用户再次登录(本方法不知道被谁调用，谁接收到通知，谁处理！)
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: WBUserShouldLoginNotification),
                    object: "bad token")
            }
            
            // error 通常比较吓人，例如编号：XXXX，错误原因一堆英文！
            print("网络请求错误 \(error)")
            
            completion(nil, false)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }

    
}
